package com.poi;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;

public class MSWordDocTool {

	public static void convertBookMarksAndSaveDocFile(String inFilePath,
			String outFilePath, Map<String, String> bookMarkValueMap) {
		Set<String> keySet = bookMarkValueMap.keySet();
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = new FileInputStream(inFilePath);
			HWPFDocument doc = new HWPFDocument(is);
			Bookmarks bookmarks = doc.getBookmarks();
			if (bookmarks != null) {
				for (int i = 0; i < bookmarks.getBookmarksCount(); i++) {
					Bookmark bookmark = bookmarks.getBookmark(i);
					for (String key : keySet) {
						if (bookmark.getName().equals(key)) {
							Range range = new Range(bookmark.getStart(),
									bookmark.getEnd(), doc);
							range.insertBefore(bookMarkValueMap.get(key));
						}
					}
				}
			}
			fos = new FileOutputStream(outFilePath);
			doc.write(fos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
